package com.verlet.springbootdemo.simple.rabbitmq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author verlet
 *    @RabbitListener 可以标注在类上面，需配合 @RabbitHandler 注解一起使用
 * @date 2020/6/27
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "rabbitmq", name = "enabled", havingValue = "true",matchIfMissing = true)
public class ReceiveHandler {
    /**
     * 监听email队列
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = RabbitmqConfig.QUEUE_INFORM_EMAIL, durable = "true"),
                    exchange = @Exchange(name = RabbitmqConfig.EXCHANGE_TOPICS_INFORM, durable = "true",
                            type = ExchangeTypes.TOPIC, ignoreDeclarationExceptions = "true"),
                    key = RabbitmqConfig.QUEUE_INFORM_EMAIL)
    )
    public void receiveEmail(String msg, Message message, Channel channel) throws IOException {
        log.info(msg);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 手工ack
        channel.basicAck(deliveryTag, false);
    }

    /**
     * 监听sms队列
     */
    @RabbitListener(queues = {RabbitmqConfig.QUEUE_INFORM_SMS})
    public void receiveSms(@Payload String msg, Channel channel, @Headers Map<String, Object> headers) throws IOException {
        log.info(msg);
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        // 手工ack
        channel.basicAck(deliveryTag, false);
    }
}
